﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UnitTestProject.Code202412.C01
{
    [TestClass]
    public class TestC02
    {
        [TestMethod]
        public void Test1()
        {
            //var realValue1 = Exchange(1314520);
            //Assert.IsTrue(realValue1 == 249036820);

            var realValue2 = Exchange(114514);
            //返回的新值最高位是1，应该是负数
            Assert.IsTrue(realValue2 == 3209822209);
        }

        /// <summary>
        /// 根据题意，改为：交换
        /// 主函数：主要是调用其它函数
        /// 类似：大纲
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        private long Exchange(long src)
        {
            //获取一个数的二进制,不足32位要补0 
            string binStr = BinaryToString(src);
            //分别获取高低16位(容易索引越界:out of range)
            string high = binStr.Substring(0, 16);
            string low = binStr.Substring(16, 16);

            //获取新的二进制字符串
            string newValue = $"{low}{high}";
            //根据二进制字符转化为整数
            var result = BinaryStringToNumber(newValue);
            return result;
        }

        /// <summary>
        /// 功能函数：一个函数，完成一个功能
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        private string BinaryToString(long number)
        {
            return Convert.ToString(number, 2).PadLeft(32, '0');
        }

        private long BinaryStringToNumber(string binaryStr)
        {
            return Convert.ToInt32(binaryStr, 2); ;
        }

        private int BinaryStringToInt2(string binaryStr)
        {
            int decimalValue = 0;
            int length = binaryStr.Length;
            for (int i = 0; i < length; i++)
            {
                if (binaryStr[length - 1 - i] == '1')
                {
                    decimalValue += (int)Math.Pow(2, i);
                }
            }
            return decimalValue;
        }

    }
}
